package com.lottoad.android.activity.mypage;

import java.util.ArrayList;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.lottoad.android.R;
import com.lottoad.android.activity.mypage.adapter.LottoAdMyPageAdapter;
import com.lottoad.android.common.BaseActivity;
import com.lottoad.android.cronos.data.CNLottoAdMyPageData;
import com.lottoad.android.cronos.datahandler.CNBaseDataParser;
import com.lottoad.android.cronos.datahandler.CNBaseDataSet;
import com.lottoad.android.cronos.datahandler.CNResultSet;
import com.lottoad.android.cronos.http.CNLottoAdApiSetEx;
import com.lottoad.android.cronos.parser.CNLottoMypageParser;
import com.lottoad.android.util.ApplicationUtils;
import com.lottoad.android.util.CNCronosLog;
import com.lottoad.android.util.LottoAdConstants;
import com.lottoad.android.util.LottoAdOverButton;

/**
 * MyPage Activity
 * @author Administrator
 *
 */
public class LottoAdMyPageActivity extends BaseActivity{
	
	private Context mContext;
	
	/**이체 신청 Button**/
	private Button mCashoutButton;
	/**신청 내역 Button**/
	private Button mChangeListButton;
	/**카카오톡 친구추천 버튼*/
	private Button mKakaoBtn;
	
	/** 저장된 로또번호 목록 리스트뷰 **/
	private ListView mListView;
	/** 목록없을시 텍스트뷰 **/
	private TextView mListEmpty;
	/** 로또번호 목록 AdpaterView **/
	private LottoAdMyPageAdapter mListAdapter;
	/** 데이터셋 **/
	private ArrayList<CNBaseDataSet> mDataSetList;
	
	/** 총 누적 적립금액 **/
	private TextView mNujukTv;
	/** 전환 신청금액 **/
	private TextView mAskTv;
	/** 이체 완료금액 **/
	private TextView mPaidTv;
	/** 이체신청 가능금액 **/
	private TextView mUsableTv;
	
	/** 해당 금액 표시 String **/
	private String mNujukMoney, mAskMoney, mPaidMoney = "", mUsableMoney = "";
	
	/** 요청 페이지 Number **/
	private int mPageNum = 1;
	/** 데이터 셋 유/무 체크 플래그 **/
	private boolean isDataSet = false;
	/** 다음페이지 유/무 체크 플래그 **/
	private boolean isNextPage = false;
	/** 비동기 작업수행 여부 체크 플래그 **/
	private boolean mNetAsyncing = false;
	/** 리스트의 마지막 포지션값 **/
	private int mListLastPosition = 0;
	
	@Override
	protected int onGetContentViewResource() {
		return R.layout.lottoad_menu_mypage;
	}

	@Override
	protected void onInit() {
		this.mContext = LottoAdMyPageGroupActivity.mContext;
	}
	
	private void buildComponent(){
		mListView = (ListView) findViewById(R.id.list_view);
		mListEmpty = (TextView) findViewById(R.id.list_empty);
		
		mKakaoBtn = (Button) findViewById(R.id.button_kakao);
		mNujukTv = (TextView) findViewById(R.id.textView_nujuk);
		mAskTv = (TextView) findViewById(R.id.textView_ask);
		mPaidTv = (TextView) findViewById(R.id.textView_paid);
		mUsableTv = (TextView) findViewById(R.id.textView_usable);
		
		mListAdapter = new LottoAdMyPageAdapter(mContext);
		mListView.setAdapter(mListAdapter);
		
		mCashoutButton = (Button) findViewById(R.id.button_cashoutput);
		mChangeListButton = (Button) findViewById(R.id.button_changelist);
		
		mCashoutButton.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Drawable getBackground = v.getBackground();
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					v.setBackgroundDrawable(LottoAdOverButton.grayimg(getBackground));
				}
				else if(event.getAction() == MotionEvent.ACTION_UP){
					getBackground.clearColorFilter();
					v.setBackgroundDrawable(getBackground);
					if(Integer.parseInt(mUsableMoney.replace(",", "")) > 10000){
						Intent intent = new Intent(mContext, LottoAdMypageCashOutActivity.class);
						intent.putExtra("usable", mUsableMoney);
						((LottoAdMyPageGroupActivity)getParent()).startChildActivity("MyPageCashOutActivity",intent);
					}
					else {
						ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), "이체가능금액이 10,000원 이상이어야 이체신청이 가능합니다.");
					}
				}
				return false;
			}
		});
		
		mChangeListButton.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Drawable getBackground = v.getBackground();
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					v.setBackgroundDrawable(LottoAdOverButton.grayimg(getBackground));
				}
				else if(event.getAction() == MotionEvent.ACTION_UP){
					getBackground.clearColorFilter();
					v.setBackgroundDrawable(getBackground);
					if(Integer.parseInt(mAskMoney.replace(",", "")) > 10000){
						Intent intent = new Intent(mContext, LottoAdMypageChangeListActivity.class);
						intent.putExtra("nujuk", mNujukMoney);
						intent.putExtra("ask", mAskMoney);
						intent.putExtra("paid", mPaidMoney);
						intent.putExtra("usable", mUsableMoney);
						
						CNCronosLog.d("nujuk =========>" + mNujukMoney);
						CNCronosLog.d("ask =========>" + mAskMoney);
						CNCronosLog.d("paid =========>" + mPaidMoney);
						CNCronosLog.d("usable =========>" + mUsableMoney);
						
						((LottoAdMyPageGroupActivity)getParent()).startChildActivity("MyPageChagneListActivity",intent);
					} else {
						ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), "이체신청한 금액이 없습니다.");
					}

				}
				return false;
			}
		});
		
		// 스크롤시 화면상 표시되는 마지막 포지션 값에 도달하면 pageNum를 +1 시켜서 목록 요청
		// 즉, 스크롤시 자동 더보기
		mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView abslistview, int i) {
				try
		        { 
					if(isDataSet)
					{
						int mLastPosition = abslistview.getLastVisiblePosition();
						CNCronosLog.d("mLastPosition : "+ mLastPosition);
						if((mLastPosition == mListLastPosition - 1) && isNextPage && !mNetAsyncing){ 
							mPageNum = mPageNum + 1;
			            	mNetAsyncing = true;
			            	onRequestData();
			            }
					}
		        }catch(Exception e){ 
		        	
		        }
			}
			
			@Override
			public void onScroll(AbsListView abslistview, int i, int j, int k) {
				
			}
		});
		
		mKakaoBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ApplicationUtils.checkPackage(mContext, LottoAdConstants.KAKAO_PACKAGE_NAME);
			}
		});
		
		onRequestData();
	}
	
	private void parsingMyPageList(Element xmlObject) throws Exception{
		
		mDataSetList = new ArrayList<CNBaseDataSet>();
		
		CNBaseDataParser parser = new CNLottoMypageParser();
		CNResultSet resultSet = parser.parse(xmlObject);
		ArrayList<CNBaseDataSet> dataSet = null;
		
		if (resultSet != null)
		{
			dataSet = resultSet.getDataSetList();
			if (dataSet != null)
			{
				int count = dataSet.size();		
				CNCronosLog.d("DataSet.size():" + count);
				for (int i = 0; i < count; i++)
				{
					CNLottoAdMyPageData data = (CNLottoAdMyPageData) dataSet.get(i);
					
					mDataSetList.add(data);
				}
			}
			
			isNextPage = mDataSetList.size() < resultSet.getTotalCount();
			isDataSet = mDataSetList.size() > 0;
			mListLastPosition =  mDataSetList.size();
		}
		
		mListAdapter.setDataSetList(mDataSetList);
		mListAdapter.notifyDataSetChanged();
		
		mNetAsyncing = false;
		
		mNujukMoney = ApplicationUtils.makeStringWithComma(resultSet.getNujukMoney(),false);
		mAskMoney = ApplicationUtils.makeStringWithComma(resultSet.getAskMoney(),false);
		mPaidMoney = ApplicationUtils.makeStringWithComma(resultSet.getPaidMoney(),false);
		mUsableMoney = ApplicationUtils.makeStringWithComma(resultSet.getUsableMoney(),false);
		
		updateUI(mNujukMoney + "원", mAskMoney + "원", mPaidMoney + "원", mUsableMoney + "원");
	}
	
	private void updateUI(String nujukMoney, String askMoney, String paidMoney, String usableMoney){
		mNujukTv.setText(nujukMoney);
		mAskTv.setText(askMoney);
		mPaidTv.setText(paidMoney);
		mUsableTv.setText(usableMoney);
		
		if(mDataSetList != null && mDataSetList.size() > 0){
			mListView.setVisibility(View.VISIBLE);
			mListEmpty.setVisibility(View.GONE);
		} else {
			mListView.setVisibility(View.GONE);
			mListEmpty.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	public String onGetAsyncRequestUrl() {
		CNCronosLog.d("onGetAsyncRequestUrl()");
		String url = null;
		
		CNLottoAdApiSetEx MnetGlobalApiSetEx = CNLottoAdApiSetEx.getInstance();
		url = MnetGlobalApiSetEx.getMyPageUrl(mContext, ApplicationUtils.getPhoneNumber(mContext),  mPageNum);
		
		CNCronosLog.d("onGetAsyncRequestUrl", "url : "+url);
		
		return url;
	}
	
	@Override
	public void onAsyncCancelRequest() 
	{
		super.hideLoadingDialog();
		CNCronosLog.d("onAsyncCancelRequest()");
	}

	@Override
	public void onAsyncDataError(Element xmlObject, String errorMessage)
	{
		super.hideLoadingDialog();
		
		NodeList rcodeNode = xmlObject.getElementsByTagName("rcode");
		String rcode = rcodeNode.item(0).getFirstChild().getNodeValue();
		
		if(!"RET0002".equals(rcode)){
			ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), errorMessage);
		} 
	}

	@Override
	public void onAsyncPreRequest()
	{
		super.showLoadingDialog(mContext);
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject)
	{
		super.hideLoadingDialog();
		
			
		try {
				parsingMyPageList(xmlObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onAsyncRequestError(int errorNumber) {
		super.hideLoadingDialog();
		
		ApplicationUtils.showOkDialog(mContext,0,getString(R.string.popup_alert), ApplicationUtils.getErrorMessage(mContext, errorNumber));
	}

	@Override
	protected void onResume() {
		super.onResume();
		buildComponent();
	}
	
}
